package com.szholly.pro.watergas_server.ps.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;  

@Controller
@RequestMapping("/DataTransfer/*")
public class OperationDataTransferController extends BaseController{ 
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 获取数据传输率统计结果
	 * create by kbb 2015-11-11
	 */
	@RequestMapping(value = "/getDataTransferStatisticsTotal")
	public void getDataTransferStatisticsTotal(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		
		HashMap<String, String> resqMap = convertHttpServletRequest(resq);	
		List<HashMap<String, String>> dataTransferList = getStationParamTransferRateList(resqMap);
		JSONArray jsonObj = JSONArray.fromObject(dataTransferList);
		outString(jsonObj.toString());
	}
	
	// 5.2.3.1.获取站点数据上传率列表
	public List<HashMap<String, String>> getStationParamTransferRateList(HashMap<String, String> resqMap) throws Exception {
		
		List<HashMap<String, String>> dataTransferList= new ArrayList<HashMap<String, String>>();		
		List<String> paramList = getStationParamList(resqMap);
		for (int i=0; i<paramList.size(); i++){
			resqMap.put("MEASURE_ITEM", paramList.get(i));
			dataTransferList.add(getParamTransferRate(resqMap));
		}
		return dataTransferList;
	}
	
	// 5.2.3.2.获取站点数据参数项列表
	public List<String> getStationParamList(HashMap<String, String> resqMap)
	{
		String strWWTP_ID = resqMap.get("WWTP_ID");
		String strSTATION_ID = resqMap.get("STATION_ID");
		String strFLOW_NAME = resqMap.get("FLOW_NAME");
		
		String[] arrWWTP_ID = strWWTP_ID.split(",");
		String[] arrSTATION_ID = strSTATION_ID.split(",");
		String[] arrFLOW_NAME = strFLOW_NAME.split(",");
		
		String strSQL = " select t1.*,  "
				+ " d1.S_DOMAINCAPTION as POLLUTANTS_NAME, d2.S_DOMAINCAPTION as FLOW_TYPE_NAME "
				+ " from BC_SITE_POLL t1 "
				+ " left join BC_ENTERPRISE_ATTR t2 on t1.WSCLC_ID = t2.EXP_NO  "
				+ " left join BC_SITE_INFO t3 on t1.SITE_ID = t3.EXP_NO "
				+ " left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = 'MONITOR_PARAM' AND d1.S_DOMAINCODE = t1.NAME ) "
				+ " left join DATA_DEFULATDOMAIN d2 on ( d2.S_DOMAINNAME = 'STATION_FLOW_TYPE' AND d2.S_DOMAINCODE = t3.FLOW_TYPE ) "
				+ " where 1=1";
		
		if (strWWTP_ID.length()>0 && arrWWTP_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrWWTP_ID.length; i++){
				if(i<arrWWTP_ID.length-1)
					strSQL = strSQL + "t1.WSCLC_ID LIKE '%"+arrWWTP_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t1.WSCLC_ID LIKE '"+arrWWTP_ID[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strSTATION_ID.length()>0 && arrSTATION_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrSTATION_ID.length; i++){
				if(i<arrSTATION_ID.length-1)
					strSQL = strSQL + "t1.SITE_ID LIKE '%"+arrSTATION_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t1.SITE_ID LIKE '%"+arrSTATION_ID[i]+"%' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strFLOW_NAME.length()>0 && arrFLOW_NAME.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrFLOW_NAME.length; i++){
				if(i<arrFLOW_NAME.length-1)
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' OR ";
				else
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		List<GlobalParameter> param = new ArrayList<GlobalParameter>();
		List<RowBase> rcdList = DataUtil.getSelectRows(strSQL, param);		// 此处关联总字典表，getList函数需重载
		if (rcdList.size()<1)
			return null;
		
		List<String> paramList = new ArrayList<String>();
		for (int i=0; i<rcdList.size(); i++){
			paramList.add(rcdList.get(i).getValue("NAME").toString());
		}
		if (paramList.size()<1)
			return null;
		
		return paramList;
	}
	
	// 5.2.3.3.获取数据项上传率
	public HashMap<String,String> getParamTransferRate(HashMap<String, String> resqMap) throws Exception{
		
		String strParam = resqMap.get("MEASURE_ITEM");
		HashMap<String,String> paramTransfer = new HashMap<String,String>();
		Set<Entry<String, String>> sets = resqMap.entrySet();  
        for(Entry<String, String> entry : sets) {  
        	paramTransfer.put(entry.getKey(), entry.getValue());
        } 
			
		long nMonitorData = getMonitorDataRcdNum(paramTransfer);
		long nStardardData = getStandardDataRcdNum(paramTransfer);
		double dTransferRate = nMonitorData/nStardardData;
		paramTransfer.put("TRANSFER_RATE", Double.toString(dTransferRate));
		paramTransfer.put("MEASURE_ITEM", strParam);
		//paramTransfer.put("POLLUTANTS_NAME", ); //污染物别名
		
		return paramTransfer;
	}
	
	// 5.2.3.4.查询数据项监测数据记录数
	public long getMonitorDataRcdNum(HashMap<String, String> resqMap){
		
		String strWWTP_ID = resqMap.get("WWTP_ID");
		String strSTATION_ID = resqMap.get("STATION_ID");
		String strFLOW_NAME = resqMap.get("FLOW_NAME");
		String strMEASURE_ITEM = resqMap.get("MEASURE_ITEM");
		String strMEASURE_START_DATE = resqMap.get("MEASURE_START_DATE");
		String strMEASURE_END_DATE = resqMap.get("MEASURE_END_DATE");
		
		String[] arrWWTP_ID = strWWTP_ID.split(",");
		String[] arrSTATION_ID = strSTATION_ID.split(",");
		String[] arrFLOW_NAME = strFLOW_NAME.split(",");
		String[] arrMEASURE_ITEM = strMEASURE_ITEM.split(",");
		
		String strSQL = " select t1.*,  "
				+ " d1.S_DOMAINCAPTION as POLLUTANTS_NAME "
				+ " from MONITOR_DATA t1 "
				+ " left join BC_SITE_DEVICE_RPT  t2 on t1.MN = t2.DEVICE_NUM   "
				+ " left join BC_SITE_INFO t3 on t2.MONITOR_POINT = t3.EXP_NO "
				+ " left join DATA_DEFULATDOMAIN d1 on ( d1.S_DOMAINNAME = 'MONITOR_PARAM' AND d1.S_DOMAINCODE = t1.PARMNAME ) "
				+ " where 1=1";
		
		if (strWWTP_ID.length()>0 && arrWWTP_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrWWTP_ID.length; i++){
				if(i<arrWWTP_ID.length-1)
					strSQL = strSQL + "t2.WSCLC_ID LIKE '%"+arrWWTP_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t2.WSCLC_ID LIKE '"+arrWWTP_ID[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strSTATION_ID.length()>0 && arrSTATION_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrSTATION_ID.length; i++){
				if(i<arrSTATION_ID.length-1)
					strSQL = strSQL + "t2.MONITOR_POINT LIKE '%"+arrSTATION_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t2.MONITOR_POINT LIKE '%"+arrSTATION_ID[i]+"%' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strFLOW_NAME.length()>0 && arrFLOW_NAME.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrFLOW_NAME.length; i++){
				if(i<arrFLOW_NAME.length-1)
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' OR ";
				else
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strMEASURE_ITEM.length()>0 && arrMEASURE_ITEM.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrMEASURE_ITEM.length; i++){
				if(i<arrMEASURE_ITEM.length-1)
					strSQL = strSQL + "t1.PARMNAME = '"+arrMEASURE_ITEM[i]+"' OR ";
				else
					strSQL = strSQL + "t1.PARMNAME = '"+arrMEASURE_ITEM[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strMEASURE_START_DATE!=null && strMEASURE_START_DATE.length()>0)
		{
			strSQL = strSQL + " AND t1.DATATIME >= to_date('"+strMEASURE_START_DATE+" 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
		}
		
		if (strMEASURE_END_DATE!=null && strMEASURE_END_DATE.length()>0)
		{
			strSQL = strSQL + "AND t1.DATATIME <= to_date('"+strMEASURE_END_DATE+" 23:59:59', 'yyyy-mm-dd hh24:mi:ss')  ";
		}
		
		List<GlobalParameter> param = new ArrayList<GlobalParameter>();
		List<RowBase> rcdList = DataUtil.getSelectRows(strSQL, param);		
				
		return rcdList.size();
	}
	
	// 5.2.3.5.获取数据项应上传数据记录数
	public long getStandardDataRcdNum(HashMap<String, String> resqMap) throws Exception{
		
		long nStationOperateTime = getStationOperateTime(resqMap);
		long getStandardDataRcdNum = nStationOperateTime/30; // 30s 为污染物数据上传频率
		return getStandardDataRcdNum;
	}
	
	// 5.2.3.6.计算企业(站点)运转时间
	public long getStationOperateTime(HashMap<String, String> resqMap) throws Exception{
		long nSewageFlowTime = getSewageFlowTime(resqMap);
		long nAcquisitionOffLineTime = getAcquisitionOffLineTime(resqMap);
		long nStationOperateTime = nSewageFlowTime + nAcquisitionOffLineTime;
		return nStationOperateTime;
	}
	
	// 5.2.3.7.计算数采仪掉线时间
	public long getAcquisitionOffLineTime(HashMap<String, String> resqMap) throws Exception{
		
		long nAcquisitionOffLineTime = 0;
		long nOffLineTime = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		List<RowBase> rcdList = getAcquisitionOffLineRcdList(resqMap);
		if (rcdList == null)
			return 0;
			
		for (int i=0; i<rcdList.size(); i++){		
			nOffLineTime = 0;
			Date dateStartTime = sdf.parse(rcdList.get(i).getValue("OFFLINE_TIME").toString()); 
			Date dateEndTime = sdf.parse(rcdList.get(i).getValue("ONLINE_TIME").toString());
			nOffLineTime = dateEndTime.getTime()-dateStartTime.getTime();
			nAcquisitionOffLineTime += (nOffLineTime/1000);   
		}
		return nAcquisitionOffLineTime;
	}
	
	// 5.2.3.8.查询数采仪掉线记录
	public List<RowBase> getAcquisitionOffLineRcdList(HashMap<String, String> resqMap){
		
		String strWWTP_ID = resqMap.get("WWTP_ID");
		String strSTATION_ID = resqMap.get("STATION_ID");
		String strFLOW_NAME = resqMap.get("FLOW_NAME");
		String strMEASURE_START_DATE = resqMap.get("MEASURE_START_DATE");
		String strMEASURE_END_DATE = resqMap.get("MEASURE_END_DATE");
		
		String[] arrWWTP_ID = strWWTP_ID.split(",");
		String[] arrSTATION_ID = strSTATION_ID.split(",");
		String[] arrFLOW_NAME = strFLOW_NAME.split(",");
		
		String strSQL = " select t1.*  "
				+ " from MONITOR_ABNORMAL t1 "
				+ " left join BC_COLLECTION_INFO t2 on t1.MN = t2.DEVICE_NUM  "
				+ " left join BC_SITE_INFO t3 on t2.SITE_ID = t3.EXP_NO "
				+ " where 1=1";
		
		if (strWWTP_ID.length()>0 && arrWWTP_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrWWTP_ID.length; i++){
				if(i<arrWWTP_ID.length-1)
					strSQL = strSQL + "t2.WSCLC_ID LIKE '%"+arrWWTP_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t2.WSCLC_ID LIKE '"+arrWWTP_ID[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strSTATION_ID.length()>0 && arrSTATION_ID.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrSTATION_ID.length; i++){
				if(i<arrSTATION_ID.length-1)
					strSQL = strSQL + "t2.SITE_ID LIKE '%"+arrSTATION_ID[i]+"%' OR ";
				else
					strSQL = strSQL + "t2.SITE_ID LIKE '%"+arrSTATION_ID[i]+"%' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strFLOW_NAME.length()>0 && arrFLOW_NAME.length>0){
			strSQL=strSQL + " AND ( ";
			
			for (int i=0; i<arrFLOW_NAME.length; i++){
				if(i<arrFLOW_NAME.length-1)
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' OR ";
				else
					strSQL = strSQL + "t3.FLOW_TYPE = '"+arrFLOW_NAME[i]+"' ";
			}
			
			strSQL=strSQL + " )";
		}
		
		if (strMEASURE_START_DATE!=null && strMEASURE_START_DATE.length()>0)
		{
			strSQL = strSQL + " AND t1.ONLINE_TIME >= to_date('"+strMEASURE_START_DATE+" 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
		}
		
		if (strMEASURE_END_DATE!=null && strMEASURE_END_DATE.length()>0)
		{
			strSQL = strSQL + "AND t1.OFFLINE_TIME <= to_date('"+strMEASURE_END_DATE+" 23:59:59', 'yyyy-mm-dd hh24:mi:ss')  ";
		}
		
		List<GlobalParameter> param = new ArrayList<GlobalParameter>();
		List<RowBase> rcdList = DataUtil.getSelectRows(strSQL, param);		
		if (rcdList.size()<1)
			return null;
		return rcdList;
	}
	
	// 5.2.3.9.计算污水排放时间
	public long getSewageFlowTime(HashMap<String, String> resqMap){
		
		long nSewageFlowDataRcdNum = getSewageFlowDataRcdNum(resqMap);
		long nSewageFlowTime = nSewageFlowDataRcdNum*30; // 30s 为流量数据上传频率
		
		return nSewageFlowTime;
	}
	
	// 5.2.3.10.查询污水流量监测数据记录数
	public long getSewageFlowDataRcdNum(HashMap<String, String> resqMap){
		HashMap<String, String> tempMap = resqMap;
		tempMap.put("MEASURE_ITEM", "B01");
		return getMonitorDataRcdNum(tempMap);
	}
	
	// 转换请求条件
	public HashMap<String, String> convertHttpServletRequest(HttpServletRequest resq) throws Exception {
		
		HashMap<String, String> resqMap = new HashMap<>();
			
		// 转换年份月份为日期
		String strMEASURE_START_DATE = "";
		String strMEASURE_END_DATE = "";
		String strMEASURE_YEAR = RequestUnit.getString("MEASURE_YEAR");
		String strMEASURE_START_MONTH = RequestUnit.getString("MEASURE_START_MONTH");
		String strMEASURE_END_MONTH = RequestUnit.getString("MEASURE_END_MONTH");
		strMEASURE_START_DATE = strMEASURE_YEAR+"-"+strMEASURE_START_MONTH+"-01";
		strMEASURE_END_MONTH = strMEASURE_YEAR+"-"+strMEASURE_END_MONTH+"-01";
		
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dateEnd = sdf.parse(strMEASURE_END_MONTH);  
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateEnd);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));  // 获取月月尾日日期
        strMEASURE_END_DATE = sdf.format(cal.getTime());
        
		resqMap.put("WWTP_ID", RequestUnit.getString("WWTP_ID"));
		resqMap.put("STATION_ID", RequestUnit.getString("STATION_ID"));
		resqMap.put("FLOW_NAME", RequestUnit.getString("FLOW_NAME"));
		resqMap.put("MEASURE_YEAR", RequestUnit.getString("MEASURE_YEAR"));
		resqMap.put("MEASURE_START_DATE", strMEASURE_START_DATE);
		resqMap.put("MEASURE_END_DATE", strMEASURE_END_DATE);
		
		return resqMap;
	}
	
	// 查询别名
	public HashMap<String, String> getFieldDomainName(HashMap<String, String> resqMap){
		return null;
	}
}
